<template>
  <div>
    <div id="app" class="row">
      <h3>批量账号分配</h3>
      <vxe-input style="position: absolute;top: 10px;right: 20px;z-index: 999;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
      <vxe-table resizable ref="xTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row :loading="loading"
        :data="configAllEmp2tableData" @sort-change="sortChange">
        <vxe-table-column type="seq" title="序号" width="60"></vxe-table-column>
        <vxe-table-column field="empName" title="姓名" :filters="[{data: ''}]" :filter-method="customStringFilterMethod"
          sortable>
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="sportName" title="运动项目" :filters="[{data: ''}]"
          :filter-method="customStringFilterMethod" sortable>
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="email" title="邮箱" :filters="[{data: ''}]" :filter-method="customStringFilterMethod"
          sortable>
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="mobile" title="手机号" :filters="[{data: ''}]" :filter-method="customStringFilterMethod"
          sortable>
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="rolName" title="权限" :filters="[{data: ''}]" :filter-method="customStringFilterMethod"
          sortable>
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="statusName" title="账号状态" :filters="statusNameFilterData" :filter-multiple="false" :filter-method="statusNameFilterMethod" sortable></vxe-table-column>
        <vxe-table-column field="" title="分配权限" sortable>
          <template #default="{ row,rowIndex }">
            <el-link v-if="row.statusId" @click="userPolicy(row,rowIndex)" type="primary" icon="el-icon-user-solid">权限设置
            </el-link>
            <el-link v-else @click="userPolicy(row,rowIndex)" type="default" icon="el-icon-user-solid">权限设置</el-link>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
        :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
        @page-change="handlePageChange">
      </vxe-pager>
      <vxe-modal v-model="showEdit" title="账号分配" width="500" min-width="600" height="80%" resize destroy-on-close>
        <vxe-form :data="editFormData" :rules="editFormRules" title-align="right" title-width="100"
          @submit="submitEditForm">
          <vxe-form-item title="名称" field="name" span="24">
            <template #default="params">
              <vxe-input v-model="params.data.name" type="text" placeholder="请输入名称" clearable></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="手机号码" field="mobile" span="24">
            <template #default="params">
              <vxe-input v-model="params.data.mobile" type="text" placeholder="请输入手机号" clearable></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="邮箱" field="email" span="24">
            <template #default="params">
              <vxe-input v-model="params.data.email" type="text" placeholder="请输入邮箱" clearable></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="密码" field="password" span="24">
            <template #default="params">
              <vxe-input v-model="params.data.password" type="text" placeholder="密码已加密,如需修改,请直接键入新密码" clearable>
              </vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="状态" field="status" span="24">
            <template #default="params">
              <vxe-select v-model="params.data.status" placeholder="请选择" clearable>
                <vxe-option value="1" label="开通"></vxe-option>
                <vxe-option value="2" label="审核"></vxe-option>
                <vxe-option value="3" label="关闭"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title="" field="" span="24">
            <template #default="params">
              <div style="display: flex;justify-content: space-between">
                <vxe-table resizable show-overflow border stripe size="mini" min-width="200" ref="allRoleTable"
                  highlight-hover-row :data="allRole" style="margin-right: 20px;">
                  <vxe-table-column field="name" title="所有权限" width="100"></vxe-table-column>
                  <vxe-table-column field="" title="" width="60" height="36" sortable>
                    <template #default="{ row }">
                      <vxe-button @click="plusPolicy(row)" type="text"><i class="vxe-icon--plus"
                          style="font-weight: bold"></i></vxe-button>
                    </template>
                  </vxe-table-column>
                </vxe-table>
                <vxe-table resizable show-overflow border stripe size="mini" min-width="200" highlight-hover-row
                  :data="currentRole">
                  <vxe-table-column field="name" title="已有权限" width="100"></vxe-table-column>
                  <vxe-table-column field="" title="" width="60" height="36" sortable>
                    <template #default="{ row }">
                      <vxe-button @click="minusPolicy(row)" type="text"><i class="vxe-icon--minus"
                          style="font-weight: bold"></i></vxe-button>
                    </template>
                  </vxe-table-column>
                </vxe-table>
              </div>
            </template>
          </vxe-form-item>
          <vxe-form-item align="center" span="24" :item-render="{}">
            <template #default>
              <vxe-button type="submit" status="my-purple" icon="el-icon-check">好</vxe-button>
              <vxe-button @click="showEdit = false" status="my-default">取消</vxe-button>
            </template>
          </vxe-form-item>
        </vxe-form>
      </vxe-modal>
    </div>
  </div>
</template>

<script>
  import { configAllEmp2, getPolicy, updateUser } from '@/api/organization.js'
  import { get_status, get_role } from '@/api/dict.js'

  export default {
    name: 'policyConfig',
    data() {
      return {
        dict_status: {},
        dict_role: this.$store.state.user.dict_role,
        configAllEmp2tableData: [],
        configAllEmp2Data: [],
        page: {
          currentPage: 1,
          pageSize: 15,
          totalResult: 0
        },
        loading: false,
        showEdit: false,
        editFormData: {
          name: '',
          mobile: '',
          email: '',
          password: '',
          status: '',
        },
        editFormRules: {
          name: [{
            required: true,
            message: '请输入名称'
          }, ],
          mobile: [{
              required: true,
              message: '请输入手机号'
            },
            {
              min: 11,
              max: 11,
              message: '手机或电话号码格式不合法'
            }
          ],
          email: [{
            required: true,
            message: '请输入邮箱'
          }, ],
          password: [{
            required: false,
            message: '请输入密码'
          }, ],
          status: [{
            required: true,
            message: '请选择状态'
          }]
        },
        allRole: [],
        currentRole: [],
        currentEmpId: null,
        currentUserId: null,
        statusNameFilterData: [{label: '开通',value: 1},{label: '审核',value: 2},{label: '关闭',value: 3}],
        filterName: '',
        searchProps: [],
        currentRow: {},
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.configAllEmp2()
      })
    },
    watch: {
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      }
    },
    methods: {
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.configAllEmp2Data.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.configAllEmp2tableData = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.configAllEmp2tableData.length,
            totalResult: this.configAllEmp2tableData.length
          }
          this.search = true
        } else {
          this.configAllEmp2tableData = this.configAllEmp2Data
          this.findList()
        }
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          get_status().then(res=>{
            this.dict_status = res
            resolve()
          })
        })
      },
      statusNameFilterMethod({
        option,
        row,
        column
      }) {
        if (option.label) {
          return this.$XEUtils.toValueString(row[column.property]).toLowerCase().indexOf(option.label) > -1
        }
        return true
      },
      customStringFilterMethod({
        option,
        row,
        column
      }) {
        if (option.data) {
          return this.$XEUtils.toValueString(row[column.property]).toLowerCase().indexOf(option.data) > -1
        }
        return true
      },
      filterEvent(option) {
        const xTable = this.$refs.xTable
        // 设置为选中状态
        option.checked = true
        // 修改条件之后，需要手动调用 updateData 处理表格数据
        xTable.updateData()
      },
      plusPolicy(row) {
        this.allRole.splice(this.allRole.indexOf(row), 1)
        this.currentRole.push(row)
        this.currentRole.sort((a, b) => {
          return a.roleId - b.roleId
        })
      },
      minusPolicy(row) {
        this.currentRole.splice(this.currentRole.indexOf(row), 1)
        this.allRole.push(row)
        this.allRole.sort((a, b) => {
          return a.roleId - b.roleId
        })
      },
      submitEditForm() {
        if (this.currentRole.length == 0) {
          this.$message({
            showClose: true,
            message: '至少选择一个权限!',
            type: 'warning'
          });
          return
        } else {
          let roleIds = []
          let roleName = []
          this.currentRole.forEach(item => {
            roleIds.push(item.roleId)
            roleName.push(this.dict_role[item.roleId%14])
          })
          let data = {
            empId: this.currentEmpId,
            email: this.editFormData.email,
            mobile: this.editFormData.mobile,
            status: this.editFormData.status,
            roleIds: roleIds.join(','),
            userId1: this.currentUserId,
            password: this.editFormData.password,
            name: this.editFormData.name,
          }
          updateUser(data).then(res=> {
            if (res.code == 200) {
              data.rolName = roleName.join(',')
              data.statusName = this.dict_status[data.status]
              data.statusId = data.status
              Object.assign(this.currentRow, data)
              this.showEdit = false
              this.$message({
                showClose: true,
                message: '账号开通成功!',
                type: 'success'
              });
            } else {
              this.$message({
                showClose: true,
                message: res.data,
                type: 'error'
              });
            }
          })
        }
      },
      userPolicy(row,rowIndex) {
        this.currentRow = row
        this.currentEmpId = row.empId
        this.currentUserId = row.userId
        this.editFormData = {
          name: row.empName,
          mobile: row.mobile,
          email: row.email,
          password: '',
          status: row.statusId,
        }
        // 获取所有权限
        getPolicy().then(res=>{
          if (res.code == 200) {
            let dict = {}
            res.data.forEach(item => {
              dict[item.name] = item.roleId
            })
            this.allRole = res.data
            this.currentRole = []
            if (row.rolName) {
              let rolNameArr = row.rolName.split(',')
              rolNameArr.forEach(item => {
                this.currentRole.push({
                  name: item,
                  roleId: dict[item]
                })
                this.allRole.forEach((item2, index) => {
                  if (item2.name == item) {
                    this.allRole.splice(index, 1)
                  }
                })
              })
              this.currentRole.sort((a, b) => {
                return a.roleId - b.roleId
              })
            }
          }
        })
        this.showEdit = true
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      configAllEmp2() {
        configAllEmp2().then(res => {
          if (res.code === 200) {
            this.configAllEmp2Data = res.data.reverse()
            this.configAllEmp2Data.forEach(item => {
              item.statusName = this.dict_status[item.statusId]
            })
            this.searchProps = Object.keys(this.configAllEmp2Data[0])
          }
        }).then(()=>{
          this.findList()
        })
      },
      sortChange() {
        if(!this.search){
          this.page.pageSize = this.configAllEmp2Data.length
          this.findList()
        }else{
          this.page.pageSize = this.configAllEmp2tableData.length
        }
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.configAllEmp2Data.length
          this.configAllEmp2tableData = this.configAllEmp2Data.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .my-green {
    color: #0da883;
  }

  vxe-button:hover {
    color: #5c998a;
  }

  .vxe-button.type--button.theme--my-purple,
  .vxe-button.type--button.theme--my-purple:hover {
    color: #fff;
  }

  .vxe-button.type--button.theme--my-purple {
    background-color: #0da883;
  }

  .vxe-button.type--button.theme--my-purple:active {
    background-color: #042f25;
  }

  .vxe-button.type--button.theme--my-default,
  .vxe-button.type--button.theme--my-default:hover {
    color: #575555;
  }
  .vxe-button.type--button.theme--my-default:active {
    background-color: #042f25;
    color: #fff;
  }
</style>
